package com.ikkong.platform.controller;

import com.ikkong.core.dao.Blade;
import com.ikkong.core.toolbox.Record;
import com.ikkong.core.toolbox.kit.DateKit;
import com.ikkong.platform.model.IntegralLog;
import com.ikkong.platform.model.MoneyLog;
import com.ikkong.playform.model.AllCard;
import com.ikkong.playform.model.Card;
import com.ikkong.playform.model.HjUser;
import com.ikkong.playform.model.Register;
import com.ikkong.system.controller.base.UrlPermissController;
import com.jfinal.template.ext.directive.Str;
import org.apache.poi.ss.formula.functions.Intercept;
import org.apache.poi.ss.usermodel.DateUtil;
import org.beetl.sql.core.kit.StringKit;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Generated by Blade.
 * 2018-09-14 21:12:29
 */
public class APIController extends UrlPermissController {
	private static String CODE = "info";
	private static String PERFIX = "info";
	private static String LIST_SOURCE = "Info.list";
	private static String BASE_PATH = "/platform/blog/";
	
    public void getSuccess() {
        this.getResponse().setHeader("Access-Control-Allow-Origin", "*");
        this.getResponse().addHeader("Access-Control-Allow-Headers", "*");
        this.getResponse().setHeader("Access-Control-Allow-Credentials", "true");
        List<Map> map = Blade.dao().select("Blog.getSuccess", Map.class, Record.create());
        for(Map mm:map){
            String msg = mm.get("msg").toString();
            msg =  msg + " 拼团成功！";
            mm.put("msg",msg);
        }
        renderJson(map);
    }

    public void testQd(){
        int id = getParaToInt("id");
        String today = getPara("today");
        if(StringKit.isNotBlank(today)){
            String year = today.split("/")[0];
            String month = today.split("/")[1];
            String day = today.split("/")[2];
            if(month.length() == 1){
                month = "0"+ month;
            }
            if(day.length() == 1){
                day = "0"+ day;
            }
            today = year + "/" + month + "/" + day;
        }
        String today2 = today.replaceAll("/","-");
        Date now = new Date();
        String  time = (now.getTime()+"").substring(0,10);
        String month = today.substring(4,8);
        month = "%"+month+"%";
        Date t = DateKit.parseDate(today2);


        String before = DateKit.getAfterDayDateByDate(t, "-1").substring(0,10);

        List<String> days = new ArrayList<>();
        List<Register> registers = Blade.create(Register.class).findBy("user_id = '" + id + "' and register_time like '"+month+"' order by register_time desc", Register.class);
        Register r = new Register();
        r.setAddtime(Integer.parseInt(time));

        r.setUser_id(id);
        r.setIntegral(3);
        r.setType(1);
        r.setStore_id(1);
        r.setRegister_time(today);
        r.setOrder_id(-1);

        if(registers.size()>0){
            for(Register rr:registers){
                days.add(rr.getRegister_time());
            }

            if(days.contains(today)){
                System.out.printf(today+"您已经签过到了");
                return;
            }else {
                Integer continuation = registers.get(0).getContinuation();
                String lastD = registers.get(0).getRegister_time().replaceAll("/","-");
                if(before.equals(lastD)){
                    r.setContinuation(continuation+1);
                }else {
                    r.setContinuation(1);
                }

            }
        }else {
            r.setContinuation(1);
        }
        boolean save = Blade.create(Register.class).save(r);


        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","已签到成功");
        Map map2 = new HashMap();
        map2.put("continuation",r.getContinuation());//连续签到天数
        map2.put("register_integral",5);
        map2.put("register_reward",10);
        map.put("data",map2);


        renderJson(map);
    }

    public void chushi(){
        Map map = new HashMap<>();
        String today = getPara("today");
        if(StringKit.isNotBlank(today)){
            String year = today.split("/")[0];
            String month = today.split("/")[1];
            String day = today.split("/")[2];
            if(month.length() == 1){
                month = "0"+ month;
            }
            if(day.length() == 1){
                day = "0"+ day;
            }
            today = year + "/" + month + "/" + day;
        }
        String month = "%"+today.substring(4,8)+"%";
        int id = getParaToInt("id");
        List<Register> registers = Blade.create(Register.class).findBy("user_id = '" + id + "' and register_time like '"+month+"' order by register_time desc", Register.class);
        List times = new ArrayList<>();




//        Integer integer = Blade.dao().selectSingle("Blog.maxCount", Record.create().set("uid", id).set("month", month), Integer.class);
        if(registers.size()>0){
//            registers.get(0).setContinuation(integer);

            for(Register rr:registers){
                times.add(Integer.parseInt(rr.getRegister_time().substring(8)));
            }
            Integer[] it = new Integer[times.size()];
            times.toArray(it);
            Arrays.sort(it);
            List<Integer> integers = Arrays.asList(it);
            List newList = new ArrayList<>();
            for(Integer itt:it){
                newList.add(today.substring(0,8)+""+itt);
            }

            //获取最大连续签到天数
            int max = 1;
            int temp = 1;
            for(int i=0;i<integers.size()-1;i++){
                if(integers.contains(integers.get(i)+1)){
                    temp++;
                }else {
                    temp = 1;
                }
                if(temp>max){
                    max = temp;
                }
            }
            registers.get(0).setContinuation(max);
            map.put("register",registers.get(0));
            map.put("registerTime",newList);
        }else {
            map.put("register",new Register());
            map.put("registerTime",times);
        }
        List<Register> istoday = Blade.create(Register.class).findBy("user_id = '" + id + "' and register_time like '"+today+"' order by addtime desc", Register.class);
        if(istoday.size()>0){
            map.put("today",istoday);
        }else {
            map.put("today",null);
        }




        Map setting = new HashMap<>();
        setting.put("id",1);
        setting.put("register_continuation",10);
        setting.put("register_integral",0);
        setting.put("register_rule",null);
        setting.put("integral_shuoming",null);
        setting.put("store_id",1);
        map.put("setting",setting);

        Map c = new HashMap<>();
        c.put("code",0);
        c.put("data",map);
        renderJson(c);
    }

    public void ismoney(){
        int id = getParaToInt("id");
        HjUser hjUser = Blade.create(HjUser.class).findById(id);
        boolean b = false;
        if(hjUser!=null){
            if(hjUser.getMoney().compareTo(new BigDecimal(1))== -1){
                b=false;
            }else {
                b=true;
            }
        }
        renderJson(b);
    }


    public void reward(){
        Date now = new Date();
        String  month = DateKit.getDay(now).substring(5, 7);

        int id = getParaToInt("id");
        int reward = getParaToInt("ward",1);
        Card firstBy = Blade.create(Card.class).findFirstBy("user_id = '" + id + "' order by id desc", Card.class);
        if(firstBy!=null){
            Integer addtime = firstBy.getAddtime();
            String add = addtime+"000";
            Date date = new Date(Long.parseLong(add));
            String day = DateKit.getDay(date);
            String substring = day.substring(5, 7);
            if(substring.equals(month)){
                renderJson(error("本月已经兑换过了！"));
                return;
            }

        }
        Card card = new Card();
        card.setStore_id(1);
        card.setUser_id(id);
        card.setAddtime(Integer.parseInt((new Date().getTime()+"").substring(0,10)));
        card.setIs_use(0);
        card.setIs_delete(0);
        card.setGoods_id(0);
        card.setOrder_id(0);

        if(reward ==1){
            AllCard byId = Blade.create(AllCard.class).findById(2);
            card.setCard_id(2);
            card.setCard_content(byId.getContent());
            card.setCard_name(byId.getName());
            card.setCard_pic_url(byId.getPic_url());
        }else if(reward ==2){
            AllCard byId = Blade.create(AllCard.class).findById(3);
            card.setCard_id(3);
            card.setCard_content(byId.getContent());
            card.setCard_name(byId.getName());
            card.setCard_pic_url(byId.getPic_url());
        }else if(reward ==3){
            AllCard byId = Blade.create(AllCard.class).findById(4);
            card.setCard_id(4);
            card.setCard_content(byId.getContent());
            card.setCard_name(byId.getName());
            card.setCard_pic_url(byId.getPic_url());
        }
        boolean save = Blade.create(Card.class).save(card);
        if (save){
            renderJson(success("领取成功"));
            return;
        }else {
            renderJson(error("领取失败"));
        }


    }
    public void buqian(){
        int id = getParaToInt("id");
        String day = getPara("day");
        String yearmonth = getPara("yearmonth");
        String ym = yearmonth.replaceAll("/","");
        if(yearmonth.length() == 7){
            yearmonth = yearmonth.substring(0,5)+ "0" + yearmonth.substring(5);
        }


        day = day.replaceAll(ym,"");
        if(day.length() == 1){
            day = "0"+ day;
        }

//        if(StringKit.isNotBlank(day)){
//            String year = day.split("/")[0];
//            String month = day.split("/")[1];
//            String day2 = day.split("/")[2];
//            if(month.length() == 1){
//                month = "0"+ month;
//            }
//            if(day.length() == 1){
//                day2 = "0"+ day2;
//            }
//            day = year + "/" + month + "/" + day2;
//        }
//        if(day.substring(4).length() == 2){
//            day = day.substring(0,4) + "/0" + day.substring(4,5)+"/0"+day.substring(5);
//        }else if(day.substring(4).length() == 3){
//
//        }
        day = yearmonth + day;
        String dayNum = day.substring(8);
        int today = Integer.parseInt(DateKit.getDay().substring(8));
        String month = "%"+day.substring(4,8)+"%";
        String  time = (new Date().getTime()+"").substring(0,10);
        Map map = new HashMap();
        Map map2 = new HashMap();
        map2.put("continuation",0);//连续签到天数
        map2.put("register_integral",0);
        map2.put("register_reward",0);
        map.put("code",0);
        map.put("msg","已签到成功");
        List<Integer> days = new ArrayList<Integer>();
        List<Register> registers = Blade.create(Register.class).findBy("user_id = '" + id + "' and register_time like '"+month+"' order by register_time desc", Register.class);
        if(Integer.parseInt(dayNum)>today){//如果补签日期大于今天
            map.put("msg","补签日期不能大于今日！");
        }else {
            if (registers.size() < 1) {
                map.put("msg", "您还未签到，不能补签！");
            } else {
                boolean issign = false;
                //当月签到的最后一天
                int max = 0;
                for (Register rr : registers) {
                    String dd = rr.getRegister_time().substring(8);

                    if (dayNum.equals(dd)) {
                        issign = true;
                    } else {
                        days.add(Integer.parseInt(dd));
                        if (Integer.parseInt(dd) > max) {
                            max = Integer.parseInt(dd);
                        }
                    }
                }
                days.add(Integer.parseInt(dayNum));
//                if(Integer.parseInt(dayNum)>max){//补签日期大于本月最大签到日期
//                    map.put("msg","您所选的日期已经签过到了！");
//                }else {
//
//                }

                int continuation = 0;
                for (int i=0;i<days.size();i++) {
                    if(days.contains(max)){
                        continuation++;
                        max = max-1;
                    }else {
                        break;
                    }
                }
                if (issign) {
                    map.put("msg", "您所选的日期已经签过到了！");
                } else {
                    Register newR = new Register();
                    newR.setUser_id(id);
                    newR.setIntegral(3);
                    newR.setType(1);
                    newR.setStore_id(1);
                    newR.setRegister_time(day);
                    newR.setOrder_id(-1);
                    newR.setAddtime(Integer.parseInt(time));
                    newR.setContinuation(continuation);
                    HjUser hjUser = Blade.create(HjUser.class).findById(id);
                    BigDecimal money = hjUser.getMoney();
                    money = money.subtract(new BigDecimal(1));
                    hjUser.setMoney(money);
                     Blade.create(HjUser.class).update(hjUser);
                    Register register = Blade.create(Register.class).findFirstBy("user_id = '" + id + "' and register_time like '" + month + "' order by register_time desc", boolean.class);
                    register.setContinuation(continuation);
                    Blade.create(Register.class).update(register);
                    boolean save = Blade.create(Register.class).save(newR);
                    if(save){
                        IntegralLog integralLog = new IntegralLog();
                        integralLog.setAddtime(Integer.parseInt(time));
                        integralLog.setContent("补签消耗余额");
                        integralLog.setIntegral(1);
                        integralLog.setStore_id(1);
                        integralLog.setUser_id(id);
                        integralLog.setExplain("余额消耗");
                        integralLog.setOperator_id(1);
                        integralLog.setOperator("admin");
                        integralLog.setUsername(hjUser.getNickname());
                        integralLog.setType(1);
                        integralLog.setPic_url("http://www.nnmlmz.com/web/uploads/image/store_1/5cd5cdfc0d73ff6d6c2275c16a51a5f0b86768fe.jpg");
                        Blade.create(IntegralLog.class).save(integralLog);
                        MoneyLog moneyLog = new MoneyLog();
                        moneyLog.setAddtime(Integer.parseInt(time));
                        moneyLog.setDesc("补签消耗余额");
                        moneyLog.setOrder_type(8);
                        moneyLog.setOrder_id(8);
                        moneyLog.setPrice(new BigDecimal(1));
                        moneyLog.setType(2);
                        moneyLog.setUser_id(id);
                        Blade.create(MoneyLog.class).save(moneyLog);
                    }
                }
            }
        }







        map.put("data",map2);
        renderJson(map);
    }

        public void isReward(){
            String uid = getPara("uid");
            Calendar   cal_1=Calendar.getInstance();//获取当前日期
            Calendar   cal_2=Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, 0);
            cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            long time=cal_1.getTimeInMillis();
            cal_2.add(Calendar.MONTH, 1);
            cal_2.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            long time2=cal_2.getTimeInMillis();
            String t1 = (time+"").substring(0,10);
            String t2 = (time2+"").substring(0,10);
            Map map = new HashMap<>();

            List<Card> cards = Blade.create(Card.class).findBy("user_id = '" + uid + "' and addtime > '"+t1+"' and addtime < '"+t2+"'", Card.class);
            if(cards.size()>0){
               map.put("code",0);
                map.put("isReward",true);
            }else {
                map.put("code",0);
                map.put("isReward",false);
            }
            renderJson(map);

        }

        public void comment(){
            Calendar   cal_1=Calendar.getInstance();//获取当前日期
            Calendar   cal_2=Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, 0);
            cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            long time=cal_1.getTimeInMillis();
            cal_2.add(Calendar.MONTH, 1);
            cal_2.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            long time2=cal_2.getTimeInMillis();
            String t1 = (time+"").substring(0,10);
            String t2 = (time2+"").substring(0,10);
            List<Map> pinglun = Blade.dao().select("Blog.pinglun", Map.class, Record.create().set("start", t1).set("over", t2));
            setAttr("pl",pinglun);
            setAttr("code","blog");
            render(BASE_PATH+"pl.html");
        }




    }
